<template>
  <div class="login-wrap">
    <h2>嗨购后台管理系统</h2>
    <el-form
      :model="ruleForm"
      class="demo-ruleForm"
      :rules="rules"
      ref="ruleFormRef"
    >
      <el-form-item prop="adminname">
        <el-input
          v-model="ruleForm.adminname"
          placeholder="username"
          :prefix-icon="User"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="ruleForm.password"
          placeholder="password"
          :prefix-icon="Lock"
          type="password"
          show-password
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm(ruleFormRef)"
          style="width: 100%"
        >
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
// form表单的时候，最好用reactive来创建变量
import { reactive, ref } from "vue";
import { User, Lock } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import axios from "axios";
import { useRouter } from "vue-router";

const router = useRouter();

interface RuleForm {
  adminname: string;
  password: string;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  adminname: "",
  password: "",
});

const rules = reactive<FormRules<RuleForm>>({
  adminname: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 通过校验
      // 发送请求到后端
      axios
        .post("http://121.89.205.189:3000/admin/admin/login", ruleForm)
        .then((response) => {
          if (response.data.code === "200") {
            ElMessage({
              message: "登录成功",
              type: "success",
            });
            // 存用户名
            sessionStorage.setItem("adminname", response.data.data.adminname);
            // 存token
            sessionStorage.setItem("token", response.data.data.token);
            sessionStorage.setItem(
              "checkedKeys",
              JSON.stringify(response.data.data.checkedkeys)
            );

            router.push("/home");
          } else {
            ElMessage.error(response.data.message);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>

<style lang="less" scoped>
.login-wrap {
  width: 300px;
  margin: 200px auto;

  h2 {
    font-size: 26px;
    text-align: center;
    margin: 20px 0;
  }
}
</style>
